/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* insertionSortList(ListNode* head) {
        ListNode* dummy = new ListNode(-1);
        dummy->next = head;
        ListNode* lastSorted = head;
        ListNode* cur = head->next;
        while (cur) {
            if (lastSorted->val <= cur->val) {
                lastSorted = lastSorted->next;
            } else {
                ListNode* tmp = dummy;
                while (tmp && tmp->next->val < cur->val) 
                    tmp = tmp->next;
                lastSorted->next = cur->next;
                cur->next = tmp->next;
                tmp->next = cur;
            }
            cur = lastSorted->next;
        }
        return dummy->next;
    }
};